<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            button {
                color: white;
                background-image: linear-gradient(
                    120deg,
                    #a1c4fd 0%,
                    #c2e9fb 100%
                );
                border: none;
                border-radius: 5px;
                width: 100px;
                height: 30px;
                cursor: pointer;
            }
            body {
                display: flex;
                background-color: #f5f5f5;
                flex-wrap: wrap;
                position: relative;
                font-family: 'Microsoft YaHei';
            }
            #box {
                width: 1300px;
                height: auto;
                margin: auto;
                background-color: white;
            }
            #addGoods {
                margin: 20px;
            }
            hr {
                height: 1px;
                width: 96%;
                border: none;
                background-color: #ccc;
            }
            .search-box {
                width: 100%;
                height: 50px;
                padding-left: 40px;
                padding-top: 20px;
            }
            #searchBtn {
                width: 70px;
                height: 27px;
            }
            #goodsName {
                width: 150px;
                height: 20px;
                border: 1px solid #ccc;
            }
            .goods-table {
                width: 1300px;
                min-height: 500px;
                margin: auto;
                margin-top: 10px;
                background-color: white;
                padding-bottom: 50px;
            }
            table {
                width: 100%;
                margin-top: 20px;
                border-collapse: collapse;
            }
            .chk {
                width: 15px;
                height: 15px;
            }
            tr {
                width: 100%;
                height: 50px;
                border-bottom: 1px solid rgb(240, 240, 240);
            }
            th {
                padding-bottom: 20px;
            }
            td {
                text-align: center;
            }
            tbody tr {
                height: 120px;
            }
            a {
                text-decoration: none;
                color: #a1c4fd;
            }
            .tips {
                width: 300px;
                height: 50px;
                font-size: 17px;
                color: white;
                background-color: #ee609c;
                border-radius: 5px;
                text-align: center;
                line-height: 50px;
                position: absolute;
                top: 3%;
                left: 40%;
                display: none;
                z-index: 9999;
            }
            img {
                width: 80px;
                height: 80px;
                vertical-align: middle;
            }
            .addGoods {
                width: 400px;
                height: 400px;
                background-color: white;
                position: absolute;
                top: 4%;
                left: 35%;
                z-index: 999;
                border-radius: 10px;
                font-weight: bold;
                padding: 30px;
                display: none;
            }
            .addGoods input {
                width: 200px;
                height: 20px;
                border: 1px solid #ccc;
                margin-top: 30px;
            }
            .addGoods input[name='isOnLine'] {
                width: 15px;
                height: 15px;
                margin-top: 10px;
                margin-left: 10px;
            }
            .mask {
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                position: absolute;
                top: 0;
                left: 0;
                display: none;
            }
            #addBtn {
                display: block;
                float: left;
                margin-left: 30px;
            }
            #offBtn {
                display: block;
                margin-top: 40px;
                margin-left: 150px;
            }
            #saveBtn {
                display: block;
                float: left;
                margin-left: 30px;
            }
            .addBtnStatus {
                display: block;
                margin-top: 40px;
            }
            .saveBox {
                display: none;
                margin-top: 40px;
            }
            #offSaveBtn {
                display: block;
                margin-top: 40px;
                margin-left: 150px;
            }
            #dels {
                margin-top: 20px;
                margin-left: 10px;
            }
            .mouseclick {
                cursor: pointer;
                color: #ee609c;
            }
            .mouseclick:hover {
                color: #a1c4fd;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <button id="addGoods">添加商品</button>
            <hr />
            <div class="search-box">
                商品名称: <input type="text" id="goodsName" />
                <button id="searchBtn">搜索</button>
            </div>
        </div>
        <div class="goods-table">
            <table>
                <thead>
                    <tr>
                        <th><input class="chk" type="checkbox" id="all" /></th>
                        <th>ID</th>
                        <th>商品</th>
                        <th class="mouseclick">价格</th>
                        <th class="mouseclick">库存</th>
                        <th class="mouseclick">销量</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <button id="dels">删除选中</button>
        </div>
        <div class="addGoods">
            商品名称： <input type="text" id="addGoodsName" />
            <br />
            商品库存：
            <input type="text" id="addGoodsStock" /><br />
            商品销量： <input type="text" id="addGoodsSold" /> <br />商品价格：
            <input type="text" id="addGoodsPrice" /> <br />是否上架：
            <input type="radio" name="isOnLine" checked value="1" />上架<input
                type="radio"
                name="isOnLine"
                value="2"
            />下架 <br />商品图片：
            <input type="text" id="addGoodsImg" />
            <br />
            <div class="addBtnStatus">
                <button id="addBtn">确定添加</button>
                <button id="offBtn">取消添加</button>
            </div>
            <div class="saveBox">
                <button id="saveBtn">保存</button>
                <button id="offSaveBtn">取消</button>
            </div>
        </div>
        <div class="tips">提示: <span id="tips">获取数据失败</span></div>
        <div class="mask"></div>
    </body>
    <script src="ajax.js"></script>
    <script>
        let thisId = null
        window.onload = function () {
            //获取商品数据
            getGoodsData()
            //添加商品
            document.getElementById('addGoods').onclick = showAddGoodsBox
            //取消添加
            document.getElementById('offBtn').onclick = offAddGoodsBox
            document.querySelector('.mask').onclick = offAddGoodsBox
            document.getElementById('offSaveBtn').onclick = offAddGoodsBox
            //确定添加
            document.getElementById('addBtn').onclick = addGoods
            //tbody
            var tbody = document.querySelector('tbody')
            tbody.onclick = tbodyFun
            //保存
            document.getElementById('saveBtn').onclick = saveGoods
            //搜索
            document.getElementById('goodsName').onkeyup = searchFun
            document.getElementById('searchBtn').onclick = searchFun
            //全选
            document.getElementById('all').onchange = allFun
            //删除选中
            document.getElementById('dels').onclick = delsFun
            document.querySelectorAll('.mouseclick')[0].onclick = sortFun
            document.querySelectorAll('.mouseclick')[1].onclick = sortFun
            document.querySelectorAll('.mouseclick')[2].onclick = sortFun
        }
        let sortObj = {
            price: 'asc',
            stock: 'asc',
            sold: 'asc',
        }
        function sortFun() {
            let data = {
                page: 1,
                limit: 1000,
            }
            if (this.innerHTML == '价格') {
                data.type = 'price'
                data.sort = sortObj.price == 'asc' ? 'desc' : 'asc'
                sortObj.price = data.sort
            }
            if (this.innerHTML == '库存') {
                data.type = 'stock'
                data.sort = sortObj.stock == 'asc' ? 'desc' : 'asc'
                sortObj.stock = data.sort
            }
            if (this.innerHTML == '销量') {
                data.type = 'sold'
                data.sort = sortObj.sold == 'asc' ? 'desc' : 'asc'
                sortObj.sold = data.sort
            }
            ajax({
                url: 'https://liu.zzgoodqc.cn/goods/sort',
                data: data,
                success: function (res) {
                    if (res.code == 200) {
                        rendder(res.data)
                    } else {
                        showTips(res.msg, 'red')
                    }
                },
            })
        }
        //批量删除
        function delsFun() {
            let checkedObj = Array.from(
                document.querySelectorAll('.chk:checked')
            )
            checkedObj.forEach((item) => {
                let id = item.getAttribute('data-id')
                delGoods(id, item)
            })
        }
        function allFun() {
            let checkAll = this.checked
            let chk = Array.from(document.getElementsByName('chk'))
            chk.forEach((item) => {
                item.checked = checkAll
            })
        }
        //商品搜索
        function searchFun() {
            // 获取搜索框的值
            if (event.keyCode == 13 || event.type == 'click') {
                let wd = document.getElementById('goodsName').value
                //获取商品数据
                if (wd) {
                    ajax({
                        url: 'https://liu.zzgoodqc.cn/goods/search',
                        type: 'post',
                        data: {
                            goods_name: wd,
                        },
                        success: function (res) {
                            if (res.code == 200) {
                                rendder(res.data)
                            } else {
                                showTips(res.msg, 'red')
                            }
                        },
                    })
                } else {
                    getGoodsData()
                }
            }
        }
        function saveGoods() {
            let status = document.querySelector(
                'input[name="isOnLine"]:checked'
            ).value
            let goodsData = {
                id: thisId,
                goods_name: addGoodsName.value || '小八爪鱼',
                stock: addGoodsStock.value || 100,
                price: addGoodsPrice.value || 100,
                status: status || 1,
                sold: addGoodsSold.value || 100,
                img:
                    addGoodsImg.value ||
                    'https://img14.360buyimg.com/n7/jfs/t1/206184/37/26048/63725/62fc9493E51311fa7/c37c6193ac9e62be.jpg',
            }
            ajax({
                type: 'post',
                url: 'https://liu.zzgoodqc.cn/goods/update',
                data: goodsData,
                success: function (res) {
                    if (res.code == 200) {
                        showTips('修改成功', 'green')
                        document.querySelector('.addBtnStatus').style.display =
                            'block'
                        document.querySelector('.saveBox').style.display =
                            'none'
                        offAddGoodsBox()
                        getGoodsData()
                    }
                },
            })
        }
        function tbodyFun() {
            if (event.target.nodeName == 'A') {
                event.preventDefault()
                let id = event.target.getAttribute('data-id')
                if (event.target.innerHTML == '删除') {
                    if (confirm('确定删除吗？')) {
                        delGoods(id, event.target)
                    }
                }
                if (event.target.innerHTML == '编辑') {
                    editGoods(id)
                }
            }
        }
        function editGoods(id) {
            ajax({
                url: 'https://liu.zzgoodqc.cn/goods/detail?id=' + id,
                success: function (res) {
                    if (res.code == 200) {
                        thisId = id
                        addGoodsName.value = res.data.goods_name
                        addGoodsStock.value = res.data.stock
                        addGoodsSold.value = res.data.sold
                        addGoodsPrice.value = res.data.price
                        addGoodsImg.value = res.data.img
                        if (res.data.status == 1) {
                            document.querySelector(
                                'input[name="isOnLine"][value="1"]'
                            ).checked = true
                        } else {
                            document.querySelector(
                                'input[name="isOnLine"][value="2"]'
                            ).checked = true
                        }
                        document.querySelector('.addBtnStatus').style.display =
                            'none'
                        document.querySelector('.saveBox').style.display =
                            'block'
                        showAddGoodsBox()
                    }
                },
            })
        }
        function delGoods(id, obj) {
            ajax({
                url: 'https://liu.zzgoodqc.cn/goods/delete?id=' + id,
                success: function (res) {
                    if (res.code == 200) {
                        showTips('删除成功', 'green')
                        obj.parentNode.parentNode.parentNode.removeChild(
                            obj.parentNode.parentNode
                        )
                    }
                },
            })
        }
        function addGoods() {
            let status = document.querySelector(
                'input[name="isOnLine"]:checked'
            ).value
            let goodsData = {
                goods_name: addGoodsName.value || '小八爪鱼',
                stock: addGoodsStock.value || 100,
                price: addGoodsPrice.value || 100,
                status: status || 1,
                sold: addGoodsSold.value || 100,
                img:
                    addGoodsImg.value ||
                    'https://img14.360buyimg.com/n7/jfs/t1/206184/37/26048/63725/62fc9493E51311fa7/c37c6193ac9e62be.jpg',
            }
            ajax({
                url: 'https://liu.zzgoodqc.cn/goods/add',
                type: 'post',
                data: goodsData,
                success: function (res) {
                    if (res.code == 200) {
                        showTips('添加成功', 'green')
                        setTimeout(() => {
                            offAddGoodsBox()
                            getGoodsData()
                        }, 2000)
                    } else {
                        showTips('添加失败-' + res.msg, 'red')
                    }
                },
            })
        }
        function showTips(msg, bgcolor) {
            tips.innerHTML = msg
            document.querySelector('.tips').style.background = bgcolor
            document.querySelector('.tips').style.display = 'block'
            setTimeout(() => {
                document.querySelector('.tips').style.display = 'none'
            }, 2000)
        }
        function offAddGoodsBox() {
            document.querySelector('.addGoods').style.display = 'none'
            document.querySelector('.mask').style.display = 'none'
        }
        function showAddGoodsBox() {
            const addBox = document.querySelector('.addGoods')
            addBox.style.display = 'block'
            const mask = document.querySelector('.mask')
            mask.style.display = 'block'
        }
        function getGoodsData() {
            ajax({
                url: 'https://liu.zzgoodqc.cn/goods/goodslist',
                type: 'get',
                success: function (res) {
                    if (res.code == 200) {
                        rendder(res.data)
                    } else {
                        tips.innerHTML = res.msg
                        document.querySelector('.tips').style.display = 'block'
                    }
                },
            })
        }
        function rendder(data) {
            if (data.length == 0) {
                document.querySelector('tbody').innerHTML =
                    '<tr><th colspan="8" style="color:#ccc;font-size:23px;">暂无数据</th></tr>'
                return
            }
            // data.sort((a, b) => {
            //     return b.id - a.id
            // })
            let html = ''
            data.forEach((item, index) => {
                html += `<tr>
                        <td><input type="checkbox" class='chk' name="chk" data-id="${
                            item.id
                        }"/></td>
                        <td>${item.id}</td>
                        <td><img src="${item.img}">${item.goods_name}</td>
                        <td style="font-weight: bold;">￥${item.price}</td>
                        <td>${item.stock}</td>
                        <td>${item.sold}</td>
                        <td>${getDate(item.created_at)}</td>
                        <td>
                            <a href="#" data-id="${item.id}">编辑</a>
                            <a href="#" data-id="${item.id}">删除</a>
                        </td>
                    </tr>`
            })
            document.querySelector('tbody').innerHTML = html
        }
        function getDate(dates) {
            let created_at = new Date(dates)
            return (
                created_at.getFullYear() +
                '-' +
                (created_at.getMonth() + 1) +
                '-' +
                created_at.getDate() +
                ' ' +
                created_at.getHours() +
                ':' +
                created_at.getMinutes() +
                ':' +
                created_at.getSeconds()
            )
        }
    </script>
</html>
